import React, { Component } from "react";
import { NavBar, Icon } from "antd-mobile";
import SearchInput from "../SearchInput/SearchInput";
import { withRouter } from "react-router-dom";
import { getCategories } from "../../data/api";
import "./Category.scss";
class Category extends Component {
  state = {
    categories: [], // 分类菜单中的数据
    select_index: 0, // 默认选中第0项
    rightContent: [], // 右边的菜单的内容
  };
  async componentDidMount() {
    let results = await getCategories();
    this.setState({
      categories: results.message,
      rightContent: results.message[0].children,
    });
  }
  // 左边菜单点击触发事件
  handleCateClick = (index) => {
    this.setState((preState) => {
      console.log(preState.categories[index].children);
      return {
        select_index: index,
        rightContent: preState.categories[index].children,
      };
    });
  };
  // 右边点击商品逻辑
  handleItemClick = (cid) => {
    this.props.history.push("productList?cid="+cid);
  }
  
  render() {
    return (
      <div className="jnCategory">
        <NavBar
          onLeftClick={() => this.props.history.go(-1)}
          icon={<Icon type="left" />}
        >
          商品分类
        </NavBar>
        <SearchInput></SearchInput>
        {/* 分类的菜单开始*/}
        <div className="jnCategoryMenu">
          <div className="categoryMenuLeft">
            {this.state.categories.map((c, index) => {
              return (
                <div
                  key={c.cat_id}
                  onClick={this.handleCateClick.bind(this, index)}
                  className={
                    this.state.select_index === index
                      ? "menuLeftItem active"
                      : "menuLeftItem"
                  }
                >
                  {c.cat_name}
                </div>
              );
            })}
          </div>
          <div className="categoryMenuRight">
            {this.state.rightContent.map((v) => {
              return (
                <div className="menuRightList clearfix" key={v.cat_id}>
                  <div className="rightListTitle">/{v.cat_name}/</div>
                  {/* 标题内容项开始 */}
                  {v.children&&v.children.map((vv) => {
                    return (
                      <div className="menuListItem" key={vv.cat_id} onClick={this.handleItemClick.bind(this,vv.cat_id)}>
                        <div className="imgWrapper">
                          <img src={vv.cat_icon} alt="" />
                        </div>
                        <span className="subTitle">{vv.cat_name}</span>
                      </div>
                    );
                  })}
                  {/* 标题内容项结束 */}
                </div>
              );
            })}
          </div>
        </div>
        {/* 分类的菜单结束*/}
      </div>
    );
  }
}
export default withRouter(Category);
